const { Web3, HttpProvider } = require('web3');
const Big = require('big.js');
const crypto = require('crypto');

const QUICKNODE_RPC_URL =
    'https://sly-snowy-resonance.bsc.quiknode.pro/df130e3b4a962f23bc90ff2233d5fcb03315655e' // BSC 主网 RPC 节点
const contractABI = require("./common/panda.json");

async function initWeb3() {
    const provider = new HttpProvider(QUICKNODE_RPC_URL);
    const web3 = new Web3(provider);
    return web3;
}

async function main() {
    try {
        const web3 = await initWeb3();

        const CONTRACT_ADDRESS = "0xadfcef048008ea4320fc7072ca06bb4744d5ee0e";
        const CONTRACT_ABI = contractABI
        // 通过Web3.js读取（示例）
        const storageValue = await web3.eth.getStorageAt(CONTRACT_ADDRESS, 0);
        const maxAddress = web3.utils.toChecksumAddress("0x" + storageValue.slice(-40));
        console.log("maxAddress:",maxAddress);
    } catch (error) {
        console.error("Error fetching events:", error);
    }
}


// 获取 `max` 的值
async function getMaxAddress() {
    try {

        const web3 = await initWeb3();

        const CONTRACT_ADDRESS = "0xadfcef048008ea4320fc7072ca06bb4744d5ee0e";
        const CONTRACT_ABI = contractABI

        const contract = new web3.eth.Contract(CONTRACT_ABI, CONTRACT_ADDRESS);
        
        // 调用合约中的 max() 方法获取 uint256 数字
        const maxValue = await contract.methods.max().call()+"";
        console.log("maxValue:",maxValue);
        
        // 转换 uint256 为地址
        const maxAddress = web3.utils.toChecksumAddress('0x' + maxValue.slice(2, 42)); // 获取前 20 字节并转换为地址格式

        //const maxAddress = web3.utils.toChecksumAddress(web3.utils.toHex(maxValue));

        console.log("Max address:", maxAddress);
    } catch (error) {
        console.error("Error fetching max address:", error);
    }
}

async function main(){
    // 假设from地址是一个以太坊地址
    const web3 = await initWeb3();

    //const fromAddress = '0x419d34D97D46Df2e0bDe380b195BD3B3b1Da0610';

    // const fromAddress = '0x36c99c953305f12cc999995c64945a9458bF50A0';
    // const fromAddress = '0xeEA0F780cA628bb7D34308FE1192E4B16a4CDd1f';
    // const fromAddress = '0xAB40Ef2D3dE890693dd82630F490654f09a54dB5';//PPT-ZF
    const fromAddress = '0x5f381B497cC64F18F8a3dDc19Fc987615c82B9eC';//P00-ZF

    // 编码地址（注意：encodePacked 会将地址按原样编码为字节数组）
    const addressBytes = Buffer.from(fromAddress.slice(2), 'hex');
    // const addressBytes = web3.eth.abi.encodePacked(fromAddress);
    const hash = crypto.createHash('sha256').update(addressBytes).digest();
    const address='0x' + hash.toString('hex');
    console.log("address:",address);

}

function computeAddressHash(address) {
    const addressBytes = web3.eth.abi.encodePacked(fromAddress);
    const hash = crypto.createHash('sha256').update(addressBytes).digest();
    return '0x' + hash.toString('hex');
  }

  main();